<template>
   <view class="container">
     <!-- 添加旅游主题背景 -->
     <image class="bg-image" src="/static/images/traval-bg.jpg" mode="aspectFill"></image>
     
     <view class="profile-content">
       <view class="profile-header">
         <view class="avatar-wrapper" @click="changeAvatar">
           <image class="avatar" :src="tempAvatarUrl"></image>
           <view class="camera-icon">
             <uni-icons type="camera" size="24" color="#fff"></uni-icons>
           </view>
         </view>
         <!-- 添加旅游主题标语 -->
         <view class="travel-slogan">
           <text>探索世界，记录旅程</text>
         </view>
       </view>
       
       <view class="profile-body">
         <!-- 添加卡片旅游图标 -->
         <view class="info-card">
           <view class="card-header">
             <uni-icons type="person" size="20" color="#007aff"></uni-icons>
             <text class="card-title">个人信息</text>
           </view>
           <view class="info-item">
             <view class="label-wrapper">
               <uni-icons type="contact" size="16" color="#666"></uni-icons>
               <text class="label">昵称</text>
             </view>
             <input class="value" v-model="tempUsername" placeholder="请输入昵称" />
           </view>
           <view class="info-item">
             <view class="label-wrapper">
               <uni-icons type="phone" size="16" color="#666"></uni-icons>
               <text class="label">手机号</text>
             </view>
             <input class="value" v-model="tempPhone" placeholder="请输入手机号" />
             <text v-if="phoneError" class="phone-error">{{phoneError}}</text>
           </view>
         </view>
       </view>
       
       <view class="button-container">
         <button class="save-btn" @click="saveChanges()">
           <uni-icons type="checkmarkempty" size="18" color="#fff"></uni-icons>
           <text>保存修改</text>
         </button>
         <button class="logout-btn" @click="logOut()">
           <uni-icons type="poweroff" size="18" color="#fff"></uni-icons>
           <text>退出登录</text>
         </button>
       </view>
     </view>
   </view>
</template>

<script>
import { ref, onMounted } from 'vue';
import {
    mapState,
    mapActions
} from 'pinia'
import {
    useUserInfoStore
} from '../../../stores/userInfo.js';

export default {
  data() {
    return {
      tempAvatarUrl: '', // 新增临时头像URL
      tempUsername: '',
      tempPhone: '',
	  phoneError:''
    }
  },
  computed: {
    ...mapState(useUserInfoStore, ['userId', 'phone', 'username', 'state', 'avatarUrl']),
  },
  created() {
    // 初始化时将store中的数据赋给临时变量
    this.tempAvatarUrl = this.avatarUrl;
    this.tempUsername = this.username;
    this.tempPhone = this.phone;
  },
  watch:{
	  tempPhone(newVal){
		  this.validatePhone(newVal);
	  }
  },
  methods: {
    ...mapActions(useUserInfoStore, ['setUserInfo']),
    changeAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 只更新临时头像URL，不立即上传
          this.tempAvatarUrl = res.tempFilePaths[0];
        },
      });
    },
	validatePhone(phone) {
	      if (!phone) {
	        this.phoneError = '';
	        return false;
	      }
	      
	      const reg = /^1[3-9]\d{9}$/;
	      if (!reg.test(phone)) {
	        this.phoneError = '请输入有效的手机号';
	        return false;
	      }
	      
	      this.phoneError = '';
	      return true;
	    },
    async saveChanges() {
		if (!this.validatePhone(this.tempPhone)) {
			console.log('444444')
		        uni.showToast({
		          title: '请输入有效的手机号',
		          icon: 'none'
		        });
		        return;
		      }
		      if (!this.tempUsername.trim()) {
				  console.log('66666')
		        uni.showToast({
		          title: '昵称不能为空',
		          icon: 'none'
		        });
		        return;
		      }
      try {
        // 保存时才上传所有修改
        const formData = {
          id: this.userId,
          phone: this.tempPhone,
          userName: this.tempUsername
        };
    
        // 如果有新头像才上传文件
        if (this.tempAvatarUrl !== this.avatarUrl) {
			console.log('111111111')
          const uploadRes = await uni.uploadFile({
            url: 'https://yangzhao.mynatapp.cc/api/updateUser',
            filePath: this.tempAvatarUrl,
            name: 'file',
            formData: formData
          });
          
          const user = JSON.parse(uploadRes.data);
		  console.log(user)
          if (user.code === 200) {
            this.setUserInfo(user.data.id, user.data.state, user.data.userName, user.data.linkTel, user.data.imgurl);
            uni.showToast({
              title: '信息更新成功',
              icon: 'success'
            });
			uni.switchTab({
				url: '/common/pages/my/my',
			})
          }else{
			  console.error('更新失败:', error);
			  uni.showToast({
			    title: '更新失败',
			    icon: 'none'
			  });
		  }
        } else {
			console.log('222222222')
			console.log(formData)
          // 没有更换头像，只更新其他信息
          const updateRes = await uni.request({
            url: 'https://yangzhao.mynatapp.cc/api/saveUserInfo',
            method: 'POST',
            data: formData
          });
          
          const user = updateRes.data;
          if (user.code === 200) {
            this.setUserInfo(user.data.id, user.data.state, user.data.userName, user.data.linkTel, this.avatarUrl);
            uni.showToast({
              title: '信息更新成功',
              icon: 'success'
            });
			uni.switchTab({
				url: '/common/pages/my/my',
			})
          }else{
			  console.error('更新失败:', error);
			  uni.showToast({
			    title: '更新失败',
			    icon: 'none'
			  });
		  }
        }
      } catch (error) {
        console.error('更新失败:', error);
        uni.showToast({
          title: '更新失败',
          icon: 'none'
        });
      }
    },
	//退出登录方法
	logOut(){
		this.setUserInfo('', 1, '', '', '/static/logo.png');
		uni.showToast({
		  title: '退出成功',
		  icon: 'success'
		});
		uni.switchTab({
			url: '/common/pages/my/my',
		})
	}
  }
}
</script>

<style scoped>
.container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  padding-bottom: 160rpx;
  background: linear-gradient(to bottom, rgba(245, 249, 255, 0.9), rgba(230, 240, 255, 0.9)); /* 添加透明度 */
  padding: env(safe-area-inset-top) env(safe-area-inset-right) 
          env(safe-area-inset-bottom) env(safe-area-inset-left);
}

.bg-image {
  position: absolute;
  width: 100%;
  height: 38vh;
  top: 0;
  left: 0;
  opacity: 0.5;
  z-index: 0;
  filter: brightness(1.1); /* 增加亮度使图片更柔和 */
}

.profile-content {
  position: relative;
  z-index: 1;
  padding: 30rpx;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.profile-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
  margin-top: 20rpx;
  position: absolute;
  top: 14vh; /* 根据背景图高度调整 */
  left: 50%;
  transform: translateX(-50%);
  z-index: 3;
}

.travel-slogan {
  margin-top: 20rpx;
  background: rgba(255, 255, 255, 0.85);
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  font-size: 28rpx;
  color: #007aff;
  font-weight: bold;
  backdrop-filter: blur(2px); /* 添加轻微模糊效果 */
}

.avatar-wrapper {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
  border-radius: 50%;
  overflow: hidden;
  border: 4rpx solid #fff;
  box-shadow: 0 8rpx 24rpx rgba(0, 90, 180, 0.3);
  background: #fff;
  z-index: 2;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.camera-icon {
	display: none;
  /* position: absolute;
  bottom: 10rpx;
  right: 10rpx;
  background: rgba(0, 122, 255, 0.8);
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  backdrop-filter: blur(5px); */
}
/* 修改后的样式 */
.profile-body {
  margin-top: 40vh; /* 与背景图高度一致 */
  padding-top: 30rpx; /* 添加顶部内边距 */
}

.info-card {
  background: rgba(255, 255, 255, 0.90);
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 60, 120, 0.1);
  /* 移除原来的margin-top */
  border: 1rpx solid rgba(0, 122, 255, 0.1);
  position: relative;
  z-index: 2;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: center; /* 添加这行使内容水平居中 */
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid rgba(0, 122, 255, 0.1);
}

.card-title {
  font-size: 32rpx;
  color: #007aff;
  font-weight: bold;
}

.info-item {
  display: flex;
  flex-direction: column;
  padding: 25rpx 0;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.info-item:last-child {
  border-bottom: none;
}

.label-wrapper {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.label {
  font-size: 28rpx;
  color: #666;
  margin-left: 10rpx;
}

.value {
  flex: 1;
  font-size: 30rpx;
  color: #333;
  background: #f8faff;
  border: 1rpx solid #d6e4ff;
  border-radius: 12rpx;
  padding: 20rpx;
  transition: all 0.3s;
}

.value:focus {
  border-color: #007aff;
  box-shadow: 0 0 0 2rpx rgba(0, 122, 255, 0.2);
}

.button-container {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  position: fixed;
  bottom: calc(40rpx + env(safe-area-inset-bottom));
  left: 30rpx;
  right: 30rpx;
  z-index: 10;
  margin-top: 40rpx; /* 增加与卡片的间距 */
}

.save-btn, .logout-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  border-radius: 45rpx;
  font-size: 32rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 90, 180, 0.2);
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.save-btn {
  background: linear-gradient(135deg, #007aff, #00a1ff);
}

.logout-btn {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.save-btn text, .logout-btn text {
  margin-left: 10rpx;
}

.save-btn:active, .logout-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.save-btn::after, .logout-btn::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(
    to bottom right,
    rgba(255, 255, 255, 0.3) 0%,
    rgba(255, 255, 255, 0) 60%
  );
  transform: rotate(30deg);
}

.phone-error {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 10rpx;
  text-align: right;
}

.decoration-icon {
  width: 60rpx;
  height: 60rpx;
}

/* 适配平板和更大屏幕 */
@media (min-width: 768px) {
  .profile-content {
    max-width: 700rpx;
    margin: 0 auto;
  }
  
  .avatar-wrapper {
    width: 200rpx;
    height: 200rpx;
  }
  
  .decoration-icon {
    width: 80rpx;
    height: 80rpx;
  }
}
</style>